"""
钉钉开放平台API使用示例

本示例展示了如何使用DingTalkAPI和DingTalkRobot类调用钉钉开放平台的各种功能。
在运行前，请确保已正确设置相关配置。
"""

import os
import json
from cn_api_adapters import DingTalkAPI, DingTalkRobot


def dingtalk_api_example():
    """
    钉钉开放平台API使用示例函数
    """
    print("钉钉开放平台API使用示例")
    print("="*50)
    
    # 1. 初始化DingTalkAPI（企业内部应用）
    try:
        print("\n1. 企业内部应用API示例:")
        # 从环境变量获取配置或直接设置
        app_key = os.getenv('DINGTALK_APP_KEY', 'your_app_key')
        app_secret = os.getenv('DINGTALK_APP_SECRET', 'your_app_secret')
        
        # 创建API实例
        dingtalk = DingTalkAPI(app_key=app_key, app_secret=app_secret, debug=True)
        
        # 获取AccessToken
        token = dingtalk.access_token
        print(f"获取AccessToken成功: {token[:10]}...")
        
        # 获取用户信息示例
        # user_id = "userid"
        # user_info = dingtalk.get_user_info(user_id)
        # print(f"用户信息: {json.dumps(user_info, ensure_ascii=False, indent=2)}")
        print("用户信息获取方法已准备好，请提供有效的user_id后调用")
        
        # 获取部门列表示例
        # depts = dingtalk.get_department_list()
        # print(f"部门列表: {json.dumps(depts, ensure_ascii=False, indent=2)}")
        print("部门列表获取方法已准备好")
        
        # 发送工作通知示例
        # notification_data = {
        #     "agent_id": 123456789,  # 应用ID
        #     "userid_list": "user1,user2",
        #     "msg": {
        #         "msgtype": "text",
        #         "text": {
        #             "content": "这是一条测试工作通知"
        #         }
        #     }
        # }
        # result = dingtalk.send_work_notification(**notification_data)
        print("工作通知发送方法已准备好，请提供有效的参数后调用")
    except Exception as e:
        print(f"企业内部应用API示例出错: {e}")
    
    # 2. DingTalkRobot使用示例
    try:
        print("\n2. 钉钉机器人示例:")
        # 方式1：使用Webhook
        webhook = os.getenv('DINGTALK_WEBHOOK', 'https://oapi.dingtalk.com/robot/send?access_token=your_token')
        robot1 = DingTalkRobot(webhook=webhook)
        
        # 方式2：使用access_token
        access_token = os.getenv('DINGTALK_ROBOT_TOKEN', 'your_robot_token')
        robot2 = DingTalkRobot(access_token=access_token)
        
        # 方式3：使用加签机器人
        # webhook = "https://oapi.dingtalk.com/robot/send?access_token=your_token"
        # secret = "your_secret"
        # robot3 = DingTalkRobot(webhook=webhook, secret=secret)
        
        # 发送文本消息
        # robot1.send_text("这是一条机器人测试消息")
        print("文本消息发送方法已准备好")
        
        # 发送Markdown消息
        # markdown_data = {
        #     "title": "测试标题",
        #     "text": "# 一级标题\n## 二级标题\n**加粗文本**"
        # }
        # robot1.send_markdown(**markdown_data)
        print("Markdown消息发送方法已准备好")
        
        # 发送链接消息
        # link_data = {
        #     "title": "测试标题",
        #     "text": "测试内容",
        #     "messageUrl": "https://www.baidu.com",
        #     "picUrl": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"
        # }
        # robot1.send_link(**link_data)
        print("链接消息发送方法已准备好")
        
        # 发送ActionCard消息
        # action_card_data = {
        #     "title": "测试标题",
        #     "text": "测试内容",
        #     "singleTitle": "查看详情",
        #     "singleURL": "https://www.baidu.com"
        # }
        # robot1.send_action_card(**action_card_data)
        print("ActionCard消息发送方法已准备好")
        
        # 发送FeedCard消息
        # feed_card_links = [
        #     {
        #         "title": "测试标题1",
        #         "messageURL": "https://www.baidu.com",
        #         "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"
        #     },
        #     {
        #         "title": "测试标题2",
        #         "messageURL": "https://www.baidu.com",
        #         "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"
        #     }
        # ]
        # robot1.send_feed_card(feed_card_links)
        print("FeedCard消息发送方法已准备好")
    except Exception as e:
        print(f"钉钉机器人示例出错: {e}")
    
    # 3. 媒体文件上传示例
    try:
        print("\n3. 媒体文件上传示例:")
        # 注意：需要先初始化DingTalkAPI实例
        # with open("image.jpg", "rb") as f:
        #     media_data = f.read()
        # result = dingtalk.upload_media("image", "image.jpg", media_data)
        # print(f"媒体上传结果: {result}")
        print("媒体文件上传方法已准备好，请提供有效的文件后调用")
    except Exception as e:
        print(f"媒体文件上传示例出错: {e}")
    
    print("\n" + "="*50)
    print("钉钉开放平台API示例演示完成")


if __name__ == "__main__":
    dingtalk_api_example()